package com.solo.quartz.service.impl;

import com.solo.common.core.base.service.impl.BasicServiceImpl;
import com.solo.quartz.api.entity.QrtzJob;
import com.solo.quartz.mapper.QrtzJobMapper;
import com.solo.quartz.service.QrtzJobService;
import com.solo.quartz.service.inner.QuartzManage;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerKey;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 定时任务 Service实现类
 * @author 十一
 * @since 2024-04-25 14:56
 * 人生若只如初见，何事秋风悲画扇
 **/
@Service
@RequiredArgsConstructor
public class QrtzJobServiceImpl extends BasicServiceImpl<QrtzJobMapper, QrtzJob> implements QrtzJobService {

    private final QrtzJobMapper qrtzJobMapper;
    private final QuartzManage quartzManage;
    private final Scheduler scheduler;

    @PostConstruct
    public void init () {
        List<QrtzJob> jobList = queryChain().list();
        jobList.forEach(quartzJob -> {
            TriggerKey triggerKey = quartzManage.getTriggerKey(quartzJob);
            try {
                CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
                if (Objects.isNull(trigger)){
                    quartzManage.createJob(quartzJob);
                } else {
                    quartzManage.updateJob(quartzJob);
                }
            } catch (SchedulerException e) {
                throw new RuntimeException(e);
            }
        });
    }
    
}
